//
//  YDPhotoPageViewController.swift
//  YDPhotoPicker
//
//  Created by alyadan on 16/8/11.
//  Copyright © 2016年 alyadan. All rights reserved.
//

import Photos
import MVVM_BaseViewController
import YD_Util
import RxSwift
import RxCocoa

class YDPhotoPageViewController: MVVM_BaseViewController {
    
    let image_back = UIImage.init(named: "YD_Photo_Picker_bundle.bundle/icon_back@3x.png")
    let image_select = UIImage.init(named: "YD_Photo_Picker_bundle.bundle/select@3x.png")
    let image_hasSelected = UIImage.init(named: "YD_Photo_Picker_bundle.bundle/hasSelected@3x.png")
    let image_unSelectedPoint = UIImage.init(named: "YD_Photo_Picker_bundle.bundle/unSelectedPoint@3x.png")
    let image_selectedPoint = UIImage.init(named: "YD_Photo_Picker_bundle.bundle/selectedPoint@3x.png")
    
    let greenColorValue = 0x11ce6e
    let lightGrayColorValue = 0xa9b7b7
    let pageViewController = UIPageViewController(transitionStyle: .scroll, navigationOrientation: .horizontal, options: [UIPageViewController.OptionsKey.interPageSpacing:20])
    
    
    var currentVCModel:YDPhotoPageVCModel{
        return vcModel.value as! YDPhotoPageVCModel
    }
    
    let backBtn  = UIButton(type: UIButton.ButtonType.custom)
    let selectBtn = UIButton(type: UIButton.ButtonType.custom)
    lazy var topControlView:UIView = {
        let x = UIView()
        x.addSubview(self.backBtn)
        x.addSubview(self.selectBtn)
        x.backgroundColor = UIColor(HEXValue: 0x444444, alpha: 0.8)
        return x
    }()
    
    
    lazy var sendBtn:UIButton = {
        let x = UIButton(type: UIButton.ButtonType.custom)
        x.setTitle("选择", for: .normal)
        x.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        x.setTitleColor(UIColor.init(HEXValue: self.greenColorValue) , for: .normal)
        return x
    }()
    
    lazy var orignalImageBtn:UIButton = {
        
        let x = UIButton(type: UIButton.ButtonType.custom)
        x.contentHorizontalAlignment = .left
        x.setTitle("原图", for: .normal)
        x.setImage(self.image_unSelectedPoint, for: .normal)
        x.titleEdgeInsets = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 0)
        x.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        x.setTitleColor(UIColor.init(HEXValue: self.lightGrayColorValue) , for: .normal)
        return x
    }()
    
    lazy var selectCountLabel:UILabel = {
        let x = UILabel()
        x.backgroundColor = UIColor(HEXValue: self.greenColorValue)
        x.textAlignment = .center
        x.text = "12"
        x.textColor = UIColor.white
        x.layer.cornerRadius = 15
        x.layer.masksToBounds = true
        return x
    }()
    
    lazy var bottomControlView:UIView = {
        let x = UIView()
        x.addSubview(self.orignalImageBtn)
        x.addSubview(self.sendBtn)
        x.addSubview(self.selectCountLabel)
        x.backgroundColor = UIColor(HEXValue: 0x444444, alpha: 0.8)
        return x
    }()
    
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        //Top
        topControlView.snp.updateConstraints {[weak self] (make) in
            make.top.left.right.equalTo(self!.view)
            make.height.equalTo(64)
        }
        
        backBtn.snp.updateConstraints {[weak self] (make) in
            make.centerY.equalTo(self!.topControlView)
            make.left.equalTo(self!.topControlView.snp.left).offset(10)
            make.height.width.equalTo(40)
        }
        
        selectBtn.snp.updateConstraints {[weak self] (make) in
            make.centerY.equalTo(self!.topControlView)
            make.right.equalTo(self!.topControlView).offset(-10)
            make.height.width.equalTo(40)
        }
        
        
        //Bottom
        bottomControlView.snp.updateConstraints {[weak self] (make) in
            make.bottom.left.right.equalTo(self!.view)
            make.height.equalTo(50)
        }
        
        orignalImageBtn.snp.updateConstraints {[weak self] (make) in
            make.centerY.equalTo(self!.bottomControlView)
            make.left.equalTo(self!.topControlView.snp.left).offset(10)
            make.height.equalTo(40)
            make.width.equalTo(160)
        }
        
        sendBtn.snp.updateConstraints {[weak self] (make) in
            make.centerY.equalTo(self!.bottomControlView)
            make.right.equalTo(self!.topControlView).offset(-10)
            make.height.equalTo(40)
        }
        selectCountLabel.snp.updateConstraints { [weak self](make) in
            make.centerY.equalTo(self!.bottomControlView)
            make.right.equalTo(self!.sendBtn.snp.left).offset(-3)
            make.height.width.equalTo(30)
        }
    }
    
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.isNavigationBarHidden = true
    }
    
    override var prefersStatusBarHidden :Bool {
        return true
    }
    
    
    
    override func setupUI() {
        
        //pageViewController
        pageViewController.dataSource = currentVCModel
        pageViewController.delegate = currentVCModel
        pageViewController.view.backgroundColor = UIColor.black
        var subViewControllers = [UIViewController]()
        subViewControllers.append(currentVCModel.assetBowerModel.creatViewController(vcIndex: 0)!)
        
        pageViewController.setViewControllers(subViewControllers, direction: .forward, animated: true) { (x:Bool) in
            //           printLog("page setViewControllers success \(x)")
        }
        
        self.addChild(pageViewController)
        pageViewController.didMove(toParent: self)
        self.view.addSubview(pageViewController.view)
        
        
        //controlView
        view.addSubview(topControlView)
        backBtn.setImage(image_back, for: .normal)
        selectBtn.setImage(image_select, for: .normal)
        
        view.addSubview(bottomControlView)
    }
    
    override func addActionTarget() {
        backBtn.rx.tap
            .asObservable()
            .bindNext {[unowned self] (_) in
                self.currentVCModel.onTapNavLeftBtn()
            }
            .addDisposableTo(disposeBag)
        
        selectBtn.rx.tap
            .asObservable()
            .bindNext { [unowned self](_) in
                self.currentVCModel.selectImage()
            }
            .addDisposableTo(disposeBag)
        
        sendBtn.rx.tap
            .asObservable()
            .bindNext { [unowned self](_) in
                self.currentVCModel.dataModel.sendAction()
            }
            .addDisposableTo(disposeBag)
        
        orignalImageBtn.rx.tap
            .asObservable()
            .bindNext { [unowned self](_) in
                self.currentVCModel.changeImageExpression()
            }
            .addDisposableTo(disposeBag)
        
    }
    
    override func bindModelData() {
        
        
        currentVCModel.isHiddenToolbars.asObservable()
            .bindNext {[unowned self] (x: Bool) in
                self.topControlView.isHidden = x
                self.bottomControlView.isHidden = x
            }
            .addDisposableTo(disposeBag)
        
        currentVCModel.dataModel.selectedAssets
            .asObservable()
            .bindNext({[unowned self] (x: [PHAsset]) in
                self.selectCountLabel.isHidden = (x.count == 0)
                self.selectCountLabel.text = String(x.count)
                if x.count == 0 {
                    self.sendBtn.setTitle("取消", for: .normal)
                } else {
                    self.sendBtn.setTitle("选择", for: .normal)
                }
            })
            .addDisposableTo(disposeBag)
        
        currentVCModel.isSelected.asObservable()
            .bindNext {[unowned self] (x: Bool) in
                
                self.selectBtn.setImage(x ? self.currentVCModel.imageSelected : self.currentVCModel.imageUnSelected, for: .normal)
            }
            .addDisposableTo(disposeBag)
        
        currentVCModel.dataModel.isUseOrignalData
            .asObservable()
            .bindNext {[unowned  self] (x: Bool) in
                self.orignalImageBtn.setTitleColor(
                    x == false ? UIColor.init(HEXValue: self.lightGrayColorValue) : UIColor(HEXValue: 313131)
                    , for: .normal)
                self.orignalImageBtn.setImage(
                    x == false ? self.image_unSelectedPoint : self.image_selectedPoint
                    , for: .normal)
            }
            .addDisposableTo(disposeBag)
        
        

        Observable.combineLatest(currentVCModel.dataModel.isUseOrignalData.asObservable(), currentVCModel.currentAssetBrowerViewModel.asObservable(), resultSelector: {($0, $1)})
            .bindNext {[unowned self] (x: Bool, y: YDPhotoAssetBrowerVCModel?) in
                if x == false {
                    self.orignalImageBtn.setTitle("原图", for: .normal)
                }else{
                    if let browerModel = y{
                        
                        browerModel.orignalImageSize.asObservable()
                            .bindNext({[unowned self] (size: Int?) in
                                if let size = size {
                                    let str = String(format: "原图(%0.2lfM)", CGFloat(size) / CGFloat(1024 * 1024))
                                    self.orignalImageBtn.setTitle(str , for: .normal)
                                }else{
                                    self.orignalImageBtn.setTitle("原图(...)" , for: .normal)
                                }
                            })
                            .addDisposableTo(self.disposeBag)
                    }
                }
            }
            .addDisposableTo(disposeBag)
        
    }
}


class YDPhotoPageVCModel: MVVM_BaseVCModel, UIPageViewControllerDelegate,UIPageViewControllerDataSource {
    
    override func viewController(vcIndex: Int) -> MVVM_BaseViewController? {
        return YDPhotoPageViewController()
    }
    
    //MARK: ----- pageViewController data
    var currentIndex = Variable<Int>(0)
    
    var currentAssetBrowerViewModel = Variable<YDPhotoAssetBrowerVCModel?>(nil)
    
    var assetArr:[PHAsset]?
    
    let isHiddenToolbars = Variable<Bool>(false)
    
    var dataModel:YDPhotoShowAlbumVCModel {
        get {
            return parentViewModel as! YDPhotoShowAlbumVCModel
        }
    }
    
    
    //control view
    var isSelected = Variable<Bool>(false)
    let imageSelected = UIImage(named: "YD_Photo_Picker_bundle.bundle/hasSelected@3x.png")
    let imageUnSelected = UIImage(named: "YD_Photo_Picker_bundle.bundle/select@3x.png")
    
    convenience init(asserts:PHFetchResult<AnyObject>?, startIndex:Int,parentVCModel:MVVM_BaseViewModel) {
        var arr = [PHAsset]()
        asserts?.enumerateObjects({ (x:AnyObject, _, _) in
            arr.append(x as! PHAsset)
        })
        self.init(assertArr:arr, startIndex:startIndex,parentVCModel: parentVCModel)
    }
    
    init(assertArr:[PHAsset]?, startIndex:Int, parentVCModel:MVVM_BaseViewModel) {
        self.assetArr = assertArr
        currentIndex.value = startIndex
        super.init(parentViewModel: parentVCModel)
    }
    
    
    override func setupModel() {
        Observable.combineLatest(currentIndex.asObservable(), dataModel.selectedAssets.asObservable(), resultSelector: {($0, $1)})
            .bindNext { [unowned self] (index:Int, selectedAssets:[PHAsset]) in
                if let currentAsset = self.assetArr?[index]{
                    self.isSelected.value = selectedAssets.contains(currentAsset)
                }
            }
            .addDisposableTo(disposeBag)
        
    }
    
    lazy var assetBowerModel:YDPhotoAssetBrowerVCModel = {
        let asset = self.assetArr?[self.currentIndex.value]
        let browerModel:YDPhotoAssetBrowerVCModel = YDPhotoAssetBrowerVCModel.init(asset: asset)
        
        browerModel.singleClickBlock = {[weak self] in
            self!.isHiddenToolbars.value = !self!.isHiddenToolbars.value
        }
        self.currentAssetBrowerViewModel.value = browerModel
        return browerModel
    }()
    
    //    var poolIndex = 0
    //    lazy var assetBrowerModelsPool = [YDPhotoAssetBrowerVCModel].init(count: 6, repeatedValue:YDPhotoAssetBrowerVCModel(asset: nil) )
    //
    //    func getModelFromPool() -> YDPhotoAssetBrowerVCModel {
    //        poolIndex += 1
    //        poolIndex = (poolIndex == assetBrowerModelsPool.count ? 0 : poolIndex)
    //        DDLogDebug("poolIndex ----- \(poolIndex)")
    //       return assetBrowerModelsPool[poolIndex]
    //    }
    
    
    func getIndex(with vc:MVVM_BaseViewController) -> Int? {
        if let asset = (vc.vcModel.value as? YDPhotoAssetBrowerVCModel)?.asset.value{
            let index = assetArr?.index(of: asset)
            return index != NSNotFound ? index : nil
        }
        return nil
    }
    
    func getViewController(currentAssetIndex:Int?, type:Int) -> UIViewController? {
        if let currentAssetIndex = currentAssetIndex{
            let nextIndex = (type == 0) ? currentAssetIndex - 1: currentAssetIndex + 1
            if nextIndex == -1 || nextIndex == assetArr!.count {
                return nil
            }
            
            let nextAsset = assetArr?[nextIndex]
            //            let browerModel = getModelFromPool()
            //
            //            browerModel.clean()
            //            browerModel.asset.value = nextAsset
            let browerModel = YDPhotoAssetBrowerVCModel(asset: nextAsset)
            
            browerModel.singleClickBlock = {[weak self] in
                self!.isHiddenToolbars.value = !self!.isHiddenToolbars.value
            }
            return  browerModel.creatViewController(vcIndex: 0)
        }
        return nil
    }
    
    
    //MARK:UIPageViewControllerDelegate
    func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
        let currentVC = (MVVM_modelController as! YDPhotoPageViewController).pageViewController.viewControllers!.first as! MVVM_BaseViewController
        self.currentAssetBrowerViewModel.value = currentVC.vcModel.value as? YDPhotoAssetBrowerVCModel
        if let index = getIndex(with: currentVC) {
            currentIndex.value = index
        }
    }
    //MARK:UIPageViewControllerDataSource
    
    func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
        let assetIndex = getIndex(with:viewController as! MVVM_BaseViewController)
        return getViewController(currentAssetIndex: assetIndex, type: 0)
    }
    
    func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
        let assetIndex = getIndex(with:viewController as! MVVM_BaseViewController)
        return getViewController(currentAssetIndex: assetIndex, type: 1)
    }
    
    //MARK:Interaction
    func selectImage() {
        self.dataModel.modifySelectedAssets(with: assetArr![currentIndex.value])
    }
    
    func changeImageExpression(){
        self.dataModel.isUseOrignalData.value =  !self.dataModel.isUseOrignalData.value
        if !isSelected.value && self.dataModel.isUseOrignalData.value{
            self.dataModel.modifySelectedAssets(with: assetArr![currentIndex.value] )
        }
    }
    
}

